#coding=utf-8
#!/usr/bin/python3
# @author:ZhaiGuiDe
# @Time:2021/6/1/ 9:28
import os,datetime
import random

from load_video_110_53.constants import MEDIA_LIST
from load_video_110_53.db_connect import MysqlClient
now_day_time = datetime.datetime.now().strftime("%Y-%m-%d")
import requests
import time as t
import gevent

ADMIN_IP="10.168.103.53"
ADMIN_PORT = "81"
ADMIN_LOGIN_URL = "/api/video_analysis/user/loginAdmin"
VIDEO_FILE_PATH = "E:\\\\\\\\zhiyinxoashi-video-110\\\\\\\\MP4\\\\\\\\"
VIDEO_CHECK_STATUS = "/api/video_analysis/video-origin/import/check/list"

class ProcessVideo:
    def get_token(self):
        #获取token
        login_url = "http://"+ADMIN_IP+":"+ADMIN_PORT+ADMIN_LOGIN_URL
        req_data = {
            "username": "admin2000:111111",
            "password": "cetcai.com"
        }
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Length": "43",
            "Content-Type": "application/x-www-form-urlencoded",
            # "Host": "10.168.103.53:81",
            "Host": ADMIN_IP+":"+ADMIN_PORT,
            "Origin": "http://"+ADMIN_IP+":"+ADMIN_PORT,
            "Pragma": "no-cache",
            "Referer": "http://"+ADMIN_IP+":"+ADMIN_PORT + "/admin/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4449.6 Safari/537.36"
        }
        res = requests.post(url=login_url,data=req_data,headers=headers).json()
        # print("获取restoken")
        token = res.get("token")
        return token

    def get_load_video_id(self):
        # 获取上传时的id
        # url = "http://10.168.103.53:81/api/video_analysis/video-origin/getId"
        url = "http://"+ADMIN_IP+":"+ADMIN_PORT+"/api/video_analysis/video-origin/getId"
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Length": "29747",
            "Content-Type": "application/x-www-form-urlencoded",
            "Host": ADMIN_IP+":"+ADMIN_PORT,
            "Origin": "http://"+ADMIN_IP+":"+ADMIN_PORT,
            "Pragma": "no-cache",
            "Referer": "http://"+ADMIN_IP+":"+ADMIN_PORT + "/admin/",
            "token":self.get_token()
        }
        form_data = {
            "section": "其他,政治",
            "labelsSource": "0",
            "title": "00a3ffd0cf483208380859b002420b",
            "videoLang": "英语",
            "info": "<p>test_data</p>",
            "searchCountry": "美国",
            "makeTime": t.strftime("%Y-%m-%d"),
            "loadTime":  t.strftime("%Y-%m-%d"),
            "tenantId": "bd88a7c8250e443bbdba644f84ddfb52",
            "downloadTenant": "禁止下载",
            "url": "www.youtube.com",
            "siteName": "youtube",
            "spiderTime":  t.strftime("%Y-%m-%d"),
            "uploadTime":  t.strftime("%Y-%m-%d"),
            "author": random.choice(MEDIA_LIST),
        }
        res = requests.post(url=url,headers=headers,data=form_data)
        print(res.json())
        return res.json()

    def read_txt(self,video_name):
        # 拿到video.mp4,去除mp4,读出和video_name同名的txt文件
        try:
            with open(VIDEO_FILE_PATH + video_name.replace(".mp4","") + ".txt","r",encoding="utf-8")as f:
                text = f.readlines()
                # # f.close()
                return str(text)
        except FileNotFoundError:
            # 如果没有这个视频的tx文本，则以w写的方式创建一个txt
            with open(VIDEO_FILE_PATH + video_name.replace(".mp4","") + ".txt","w",encoding="utf-8")as f:
                text = f.readlines()
                print("该视频 %s 没有txt文本，创建一个空的文本")
                return text


    def load_video(self,video_name):
        # 导入视频
        now_day_time = datetime.datetime.now().strftime("%Y-%m-%d")
        # url = "http://10.168.103.53:81/api/video_analysis/video-origin/insert"
        url = "http://"+ADMIN_IP+":"+ADMIN_PORT+"/api/video_analysis/video-origin/insert"
        headers = {
            "Accept": "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate",
            "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
            "Cache-Control": "no-cache",
            "Connection": "keep-alive",
            "Content-Length": "33500233",
            # "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundaryOt7Tr0Ev73b3Jxyx",
            # "Host": "10.168.103.53:81",
            "Host": ADMIN_IP+":"+ADMIN_PORT,
            "Origin": "http://"+ADMIN_IP+":"+ADMIN_PORT,
            "Pragma": "no-cache",
            "Referer": "http://"+ADMIN_IP+":"+ADMIN_PORT + "/admin/",
            "token": self.get_token(),
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4449.6 Safari/537.36",
        }
        video_all_path = VIDEO_FILE_PATH + video_name
        # video_file = "E:\\\\\\\\zhiyinxoashi-video-110\\\\\\\\MP4\\\\\\\\"
        # video_name = "0a2a580b00ceadd0524500eb3c04e660.mp4"

        files = {"file" : open(video_all_path,"rb")}
        data  = {
            "file":"",
            "section": "其他",
            "labelsSource": "0",
            "title": video_name[0:20],
            # "title": "0a2a580b00ceadd052450",
            "videoLang": "英语",
            # "info": read_txt(video_name),
            # "info":"<p>this is name </p>",
            "info":"<p>" +str(self.read_txt(video_name))+"</p>",
            "searchCountry": "美国,英国",
            "makeTime": now_day_time,
            "loadTime": now_day_time,
            "tenantId": "bd88a7c8250e443bbdba644f84ddfb52",
            "downloadTenant": "禁止下载",
            "url": "www.youtube.com",
            "siteName": "youtube",
            "spiderTime": now_day_time,
            "uploadTime": now_day_time,
            # "author": "KyodoNews",
            "author": random.choice(MEDIA_LIST),
            "id": self.get_load_video_id(),
        }
        print("---------",data)
        try:
            res = requests.post(url = url,data=data,headers=headers,files=files)
            print(res.json())
        except Exception as e:
            print(e)
        t.sleep(2)

if __name__ == '__main__':
    msc = MysqlClient()
    provideo = ProcessVideo()
    # # 查询sql为0的则是没有上传过的，

    select_all_video_sql = """
                select video_name from test_video_file where flag=0
    """
    for video_name in msc.dataSelect(select_all_video_sql):
        video_name=video_name[0]
        # gevent.joinall([
        #     gevent.spawn(load_video,video_name)
        # ])
        provideo.load_video(video_name)
        msc.update_flag(video_name)
        print("修改视频%s---->状态为flag为1" % video_name)
    print("===========上传完毕！===========")











